package com.soft.line.service.impl;

import com.soft.line.mapper.AppletCommonMapper;
import com.soft.line.service.AppletCommonService;
import com.soft.line.util.MP.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

/**
 * 小程序 公用
 *
 * @author wpb
 * @version 1.0
 * @date 2020/6/1 9:10
 */
@Slf4j
@Service
public class AppletCommonServiceImpl implements AppletCommonService {

    /**
     * 文件上传路径  例如：D盘下的路径
     */
    @Value(value = "${uploadFileDir}")
    private String uploadFileDir;


    @Autowired
    private AppletCommonMapper appletCommonMapper;

    @Override
    public AjaxResult getBaseData() {
        //返回数据
        Map<String, List<Map<String, String>>> map = new HashMap<>(0);

        //数据库数据
        List<Map<String, String>> mapList = appletCommonMapper.codeDetailMap();

        if (mapList.size() > 0) {

            Set<String> codeTypeSet = new HashSet<>();

            for (Map<String, String> mapData : mapList) {
                codeTypeSet.add(mapData.get("codeType"));
            }

            for (String codeType : codeTypeSet) {
                //枚举数据集合
                List<Map<String, String>> listData = new ArrayList<>();
                for (Map<String, String> mapInitial : mapList) {
                    //枚举数据
                    Map<String, String> mapData = new HashMap<>(0);

                    if (codeType.equals(mapInitial.get("codeType"))) {
                        mapData.put("codeDetail", mapInitial.get("codeDetail"));
                        mapData.put("codeContent1", mapInitial.get("codeContent1"));
                        listData.add(mapData);
                    }

                }
                map.put(codeType, listData);
            }
        } else {
            return AjaxResult.error();
        }
        return AjaxResult.success(map);
    }


    @Override
    public AjaxResult uploadContractAttach(MultipartFile file, int id, String fileName, String modifyPerson) {
        File uploadRootFileDir = new File(uploadFileDir);
        File fileDir = new File(uploadRootFileDir.getAbsolutePath(), "contract/" + id);

        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        //校验文件重名，不入附件表 但会删除老的，上传新的
        boolean checkName = false;

        //文件夹中已存在的文件
        File[] existingFiles = fileDir.listFiles();

        for (File existingFile : existingFiles) {
            //文件名一样就先删除
            if (existingFile.getName().equals(fileName)) {
                checkName = true;
                existingFile.delete();
            }
        }

        File newFile = new File(fileDir.getAbsolutePath(), fileName);

        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return AjaxResult.error("上传文件失败");
        }

        if (!checkName) {
            //url地址   attachmentUrl
            String attachmentUrl = "contract/" + id + "/" + fileName;
            //标记时间
            Date modifyTime = new Date();

            //附件类型（1：合同，2：证书）
            String type = "1";
            //添加到附件表中
            int i = appletCommonMapper.addAnnex(fileName, attachmentUrl, modifyPerson, modifyTime, type, id);
            //入库是否成功
            if (i != 1) {
                return AjaxResult.error("文件入库失败，请再次上传");
            }
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult uploadCertificateAttach(MultipartFile file, int id, String fileName, String modifyPerson) {

        File uploadRootFileDir = new File(uploadFileDir);
        File fileDir = new File(uploadRootFileDir.getAbsolutePath(), "certificate/" + id);

        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        //校验文件重名，不入附件表 但会删除老的，上传新的
        boolean checkName = false;

        //文件夹中已存在的文件
        File[] existingFiles = fileDir.listFiles();

        for (File existingFile : existingFiles) {
            //文件名一样就先删除
            if (existingFile.getName().equals(fileName)) {
                checkName = true;
                existingFile.delete();
            }
        }

        File newFile = new File(fileDir.getAbsolutePath(), fileName);

        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return AjaxResult.error("上传文件失败");
        }

        if (!checkName) {
            //url地址   attachmentUrl
            String attachmentUrl = "certificate/" + id + "/" + fileName;
            //标记时间
            Date modifyTime = new Date();

            //附件类型（1：合同，2：证书）
            String type = "2";
            //添加到附件表中
            int i = appletCommonMapper.addAnnex(fileName, attachmentUrl, modifyPerson, modifyTime, type, id);
            //入库是否成功
            if (i != 1) {
                return AjaxResult.error("文件入库失败，请再次上传");
            }
        }
        return AjaxResult.success();
    }
}
